<?php

namespace app\merchant\controller\api;
use app\Request;
use app\merchant\model\system\{
    SystemAttachment as SystemAttachmentModel, SystemAttachmentCategory as Category
};
use crmeb\services\{JsonService as Json,
    UtilService as Util
};
use crmeb\services\upload\Upload;
use think\Response;

/**
 * TODO 附件控制器
 * Class Images
 * @package app\merchant\controller\widget
 */
class Images
{
    public function __construct()
    {
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Mer-id,Authori-zation,Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With");
        header('Access-Control-Allow-Methods: GET,POST,PATCH,PUT,DELETE,OPTIONS,DELETE');
    }

    /**
     * 获取图片列表
     */
    public function get_image_list(Request $request)
    {
        $mer_id = trim(ltrim($request->header('Mer-id')));
        $where = Util::getMore([
            ['page', 1],
            ['limit', 18],
            ['pid', 0]
        ]);
        $where['mer_id'] = $mer_id;
        return Json::successful(SystemAttachmentModel::getImageList($where));
    }

    /**
     * 获取分类
     */
    public function get_image_cate(Request $request)
    {
        $name = $request->param('name');
        $mer_id = trim(ltrim($request->header('Mer-id')));
        return Json::successful(Category::getAll($name,$mer_id));
    }


    /**
     * 图片管理上传图片
     * @return \think\response\Json
     */
    public function upload(Request $request)
    {
        if($request->isOptions()) {
            return \think\Response::create('ok')->code(200)->header([
                'Access-Control-Allow-Origin' => '*',
                'Access-Control-Allow-Headers' => 'Mer-id,Authori-zation,Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
                'Access-Control-Allow-Methods' => 'GET,POST,PATCH,PUT,DELETE,OPTIONS,DELETE',
            ]);
        }
        $mer_id      = trim(ltrim($request->header('Mer-id')));
        $pid         = $request->param('pid', session('pid'));
        $upload_type = $request->param('upload_type', sys_config('upload_type', 1));
        try {
            $path = make_path('attach', 2, true);
            $upload = new Upload((int)$upload_type, [
                'accessKey' => sys_config('accessKey'),
                'secretKey' => sys_config('secretKey'),
                'uploadUrl' => sys_config('uploadUrl'),
                'storageName' => sys_config('storage_name'),
                'storageRegion' => sys_config('storage_region'),
            ]);
            $res = $upload->to($path)->validate()->move("file",$mer_id);
            if ($res === false) {
                return Json::fail('上传失败：' . $upload->getError());
            } else {
                $fileInfo = $upload->getUploadInfo();
                if ($fileInfo) {
                    $aliyun_domain          = "http://img.sichuanapp.com/";
                    $fileInfo['dir']        = $aliyun_domain.$fileInfo['name'];
                    $fileInfo['thumb_path'] = $aliyun_domain.$fileInfo['name'];
                    SystemAttachmentModel::attachmentAdd($fileInfo['name'], $fileInfo['size'], $fileInfo['type'], $fileInfo['dir'], $fileInfo['thumb_path'], $pid, $upload_type, $fileInfo['time'],1,$mer_id);
                }
                return Json::successful('上传成功', ['src' => $fileInfo['dir']]);
            }
        } catch (\Exception $e) {
            return  Json::fail('上传失败：' . $e->getMessage());
        }
    }

    /**
     * ajax 提交删除
     */
    public function delete_image(Request $request)
    {
        $image_id = $request->param('image_id');
        if(empty($image_id))
            Json::fail('还没选择要删除的图片呢？');
        try{
            $image_id_arr = json_decode($image_id,true);
        }catch (\Exception $e){
            Json::fail('图片数据有误');
        }
        foreach ($image_id_arr as $v){
            self::delete_img_and_data($v);
        }
        Json::successful('删除成功');
    }

    //删除图片
    public function delete_img_and_data($att_id)
    {

        $attinfo = SystemAttachmentModel::get($att_id);
        if ($attinfo) {
            try {
                $upload = new Upload((int)$attinfo['image_type'], [
                    'accessKey' => sys_config('accessKey'),
                    'secretKey' => sys_config('secretKey'),
                    'uploadUrl' => sys_config('uploadUrl'),
                    'storageName' => sys_config('storage_name'),
                    'storageRegion' => sys_config('storage_region'),
                ]);
                if ($attinfo['image_type'] == 1) {
                    if (strpos($attinfo['att_dir'], '/') == 0) {
                        $attinfo['att_dir'] = substr($attinfo['att_dir'], 1);
                    }
                    $upload->delete($attinfo['att_dir']);
                } else {
                    $upload->delete($attinfo['name']);
                }
            } catch (\Throwable $e) {
            }
            SystemAttachmentModel::where('att_id', $att_id)->delete();
        }
    }




    /**
     * 移动图片分类操作
     */
    public function move_image_cate()
    {
        $data = Util::postMore([
            'pid',
            'imgaes'
        ]);
        if ($data['imgaes'] == '') return Json::fail('请选择图片');
        if (!$data['pid']) return Json::fail('请选择分类');
        $res = SystemAttachmentModel::where('att_id', 'in', $data['imgaes'])->update(['pid' => $data['pid']]);
        if ($res)
            Json::successful('移动成功');
        else
            Json::fail('移动失败！');
    }



    /**
     * 添加分类
     */
    public function save_cate(Request $request)
    {
        $mer_id = trim(ltrim($request->header('Mer-id')));
        $data['pid'] = $request->param('pid');
        $data['name'] = $request->param('name');
        if (empty($data['name'])) {
            return Json::fail('分类名称不能为空！');
        }
        $data['mer_id'] = $mer_id;
        $res = Category::create($data);
        if ($res)
            return Json::successful('添加成功');
        else
            return Json::fail('添加失败！');

    }


    /**
     * 分类重命名
     */
    public function update_cate()
    {
        $data = Util::postMore([
            'name',
            'id',
        ]);
        if(!$data['name']) return Json::fail('请输入分类名称');
        Category::edit($data,$data['id']);
        return Json::successful('编辑成功!');
    }

    /**
     * 删除分类
     */
    public function delete_cate(Request $request){
        $id = $request->param('id');
        if(!$id)  Json::fail('分类id不能为空');
        $chdcount = Category::where('pid',$id)->count();
        if($chdcount) return Json::fail('有子栏目不能删除');
        $chdcount = SystemAttachmentModel::where('pid',$id)->count();
        if($chdcount) return Json::fail('栏目内有图片不能删除');
        if(Category::del($id))
            Json::successful('删除成功!');
        else
            Json::fail('删除失败');
    }
}
